﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 销售订单表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class SalesordersService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Salesorders> _salesordersRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public SalesordersService(SqlSugarRepository<Salesorders> salesordersRep, ISqlSugarClient sqlSugarClient)
    {
        _salesordersRep = salesordersRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询销售订单表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询销售订单表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<SalesordersOutput>> Page(PageSalesordersInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _salesordersRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.BillNumber.Contains(input.Keyword) || u.Contact.Contains(input.Keyword) || u.Contacts.Contains(input.Keyword) || u.Remark.Contains(input.Keyword) || u.GoodsSold.Contains(input.Keyword) || u.UploadAttachments.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.BillNumber), u => u.BillNumber.Contains(input.BillNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contact), u => u.Contact.Contains(input.Contact.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contacts), u => u.Contacts.Contains(input.Contacts.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.GoodsSold), u => u.GoodsSold.Contains(input.GoodsSold.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.UploadAttachments), u => u.UploadAttachments.Contains(input.UploadAttachments.Trim()))
            .WhereIF(input.DocumentStatusId != null, u => u.DocumentStatusId == input.DocumentStatusId)
            .WhereIF(input.DateOfSaleRange?.Length == 2, u => u.DateOfSale >= input.DateOfSaleRange[0] && u.DateOfSale <= input.DateOfSaleRange[1])
            .WhereIF(input.ClientNameId != null, u => u.ClientNameId == input.ClientNameId)
            .WhereIF(input.DepartmentId != null, u => u.DepartmentId == input.DepartmentId)
            .WhereIF(input.HeadOfSales != null, u => u.HeadOfSales == input.HeadOfSales)
            .LeftJoin<Organization>((u, clientName) => u.ClientNameId == clientName.Id)
            .LeftJoin<Organization>((u, clientName, department) => u.DepartmentId == department.Id)
            .LeftJoin<UserManagement>((u, clientName, department, headOfSales) => u.HeadOfSales == headOfSales.Id)
            .Select((u, clientName, department, headOfSales) => new SalesordersOutput
            {
                Id = u.Id,
                BillNumber = u.BillNumber,
                DocumentStatusId = u.DocumentStatusId,
                DateOfSale = u.DateOfSale,
                ClientNameId = u.ClientNameId,
                Contact = u.Contact,
                Contacts = u.Contacts,
                DepartmentId = u.DepartmentId,
                DepartmentFkDisplayName = $"{department.OrganizationName}",
                HeadOfSales = u.HeadOfSales,
                HeadOfSalesFkDisplayName = $"{headOfSales.UserName}",
                Remark = u.Remark,
                GoodsSold = u.GoodsSold,
                UploadAttachments = u.UploadAttachments,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取销售订单表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取销售订单表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Salesorders> Detail([FromQuery] QueryByIdSalesordersInput input)
    {
        return await _salesordersRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加销售订单表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加销售订单表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddSalesordersInput input)
    {
        var entity = input.Adapt<Salesorders>();
        return await _salesordersRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新销售订单表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新销售订单表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateSalesordersInput input)
    {
        var entity = input.Adapt<Salesorders>();
        await _salesordersRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除销售订单表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除销售订单表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteSalesordersInput input)
    {
        var entity = await _salesordersRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _salesordersRep.FakeDeleteAsync(entity);   //假删除
        //await _salesordersRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除销售订单表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除销售订单表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteSalesordersInput> input)
    {
        var exp = Expressionable.Create<Salesorders>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _salesordersRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _salesordersRep.FakeDeleteAsync(list);   //假删除
        //return await _salesordersRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataSalesordersInput input)
    {
        var clientNameIdData = await _salesordersRep.Context.Queryable<Organization>()
            .InnerJoinIF<Salesorders>(input.FromPage, (u, r) => u.Id == r.ClientNameId)
            .Select(u => new {
                Value = u.Id,

            }).ToListAsync();
        var departmentIdData = await _salesordersRep.Context.Queryable<Organization>()
            .InnerJoinIF<Salesorders>(input.FromPage, (u, r) => u.Id == r.DepartmentId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.OrganizationName}"
            }).ToListAsync();
        var headOfSalesData = await _salesordersRep.Context.Queryable<UserManagement>()
            .InnerJoinIF<Salesorders>(input.FromPage, (u, r) => u.Id == r.HeadOfSales)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "clientNameId", clientNameIdData },
            { "departmentId", departmentIdData },
            { "headOfSales", headOfSalesData },
        };
    }
    
    /// <summary>
    /// 导出销售订单表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出销售订单表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageSalesordersInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportSalesordersOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "销售订单表导出记录");
    }
    
    /// <summary>
    /// 下载销售订单表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载销售订单表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportSalesordersOutput>(), "销售订单表导入模板", (_, info) =>
        {
            
            if (nameof(ExportSalesordersOutput.DepartmentFkDisplayName) == info.Name) return _salesordersRep.Context.Queryable<Organization>().Select(u => $"{u.OrganizationName}").Distinct().ToList();
            if (nameof(ExportSalesordersOutput.HeadOfSalesFkDisplayName) == info.Name) return _salesordersRep.Context.Queryable<UserManagement>().Select(u => $"{u.UserName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入销售订单表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入销售订单表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportSalesordersInput, Salesorders>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 客户名称

                    // 链接 销售部门
                    var departmentIdLabelList = pageItems.Where(x => x.DepartmentFkDisplayName != null).Select(x => x.DepartmentFkDisplayName).Distinct().ToList();
                    if (departmentIdLabelList.Any()) {
                        var departmentIdLinkMap = _salesordersRep.Context.Queryable<Organization>().Where(u => departmentIdLabelList.Contains($"{u.OrganizationName}")).ToList().ToDictionary(u => $"{u.OrganizationName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.DepartmentId = departmentIdLinkMap.GetValueOrDefault(e.DepartmentFkDisplayName ?? "");
                            if (e.DepartmentId == null) e.Error = "销售部门链接失败";
                        });
                    }
                    // 链接 销售负责人
                    var headOfSalesLabelList = pageItems.Where(x => x.HeadOfSalesFkDisplayName != null).Select(x => x.HeadOfSalesFkDisplayName).Distinct().ToList();
                    if (headOfSalesLabelList.Any()) {
                        var headOfSalesLinkMap = _salesordersRep.Context.Queryable<UserManagement>().Where(u => headOfSalesLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.HeadOfSales = headOfSalesLinkMap.GetValueOrDefault(e.HeadOfSalesFkDisplayName ?? "");
                            if (e.HeadOfSales == null) e.Error = "销售负责人链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Salesorders>>();
                    
                    var storageable = _salesordersRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.BillNumber?.Length > 50, "销售单号长度不能超过50个字符")
                        .SplitError(it => it.Item.Contact?.Length > 50, "联系人长度不能超过50个字符")
                        .SplitError(it => it.Item.Contacts?.Length > 11, "联系方式长度不能超过11个字符")
                        .SplitError(it => it.Item.Remark?.Length > 200, "备注长度不能超过200个字符")
                        .SplitError(it => it.Item.GoodsSold?.Length > 32, "销售货品明细长度不能超过32个字符")
                        .SplitError(it => it.Item.UploadAttachments?.Length > 200, "上传附近长度不能超过200个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
